package mware_lib;

public class NameServiceImpl extends NameService {
    private Communication communication;
    private ObjectReferences objectReferences;
    private String splitString = Config.splitString;

    public NameServiceImpl(ObjectReferences objectReferences, Communication communication) {
        if(Config.DEBUGGER) System.out.println("new local NameServiceImpl");
        this.objectReferences = objectReferences;
        this.communication = communication;
    }

    @Override
    public void rebind(Object servant, String name) {
        if(Config.DEBUGGER) System.out.println("local NameServiceImpl mit servant: " + servant.getClass() + " und name: " + name);
        NameServiceMessage nameServiceMessage = new NameServiceMessage("rebind", name,
                communication.getHost(), objectReferences.getPort(), servant.getClass().toString(), servant.hashCode());
        objectReferences.saveRef(nameServiceMessage, servant);
        communication.send(nameServiceMessage.sendMsg());
    }

    @Override
    public Object resolve(String name) {
        if(Config.DEBUGGER) System.out.println("local NameServiceImpl mit name: " + name);
        NameServiceMessage nameServiceMessage = new NameServiceMessage("resolve", name);
        Object response = communication.sendAndReceive(nameServiceMessage.sendMsg());
        String nameServiceMessageString = (String) response;
        String[] nsmSplit =  nameServiceMessageString.split(splitString);
        nameServiceMessage = new NameServiceMessage(nsmSplit[0],nsmSplit[1],nsmSplit[2],Integer.parseInt(nsmSplit[3]),nsmSplit[4],Integer.parseInt(nsmSplit[5]));
        return nameServiceMessage;
    }
}
